package dongze.com.ckdj.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.EditMassLossRecordActivity;
import dongze.com.ckdj.adapter.MassLossRecordListAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.response.QueryMassLossRecordsResponse;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/9/26.
 */

public class MassLossRecordFragment extends ProcessableFragment {
    private static final int REQUEST_RECORD = 9998;
    @Inject
    VehicleInformationDetail vehicleInformationDetail;

    @BindView(R.id.record_list)
    ListView listview;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null && getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else if (savedInstanceState != null) {
            vehicleInformationDetail = new Gson().fromJson(savedInstanceState.getString(VehicleInformationDetail.class.getCanonicalName()), VehicleInformationDetail.class);
        }

        if (vehicleInformationDetail == null) {
            Toast.makeText(getActivity(), "车架号信息读取失败", Toast.LENGTH_SHORT).show();
            getFragmentManager().beginTransaction().remove(this).commit();
        }
    }

    @Nullable
    @Override
    protected View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_mass_loss_record, container, false);
        ButterKnife.bind(this, root);
        load();
        return root;
    }

    private void load() {
        mapUtil.getMassLossRecords(vehicleInformationDetail.getVin(), new DisposableObserver<List<QueryMassLossRecordsResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(final List<QueryMassLossRecordsResponse> value) {
                listview.setAdapter(new MassLossRecordListAdapter(MassLossRecordFragment.this, mapUtil, value, new MassLossRecordListAdapter.OnEditListener() {
                    @Override
                    public void onDelete(final QueryMassLossRecordsResponse res) {
                        mapUtil.deleteMassLossRecord(String.format("%d", res.getId()), new DisposableObserver<String>() {
                            @Override
                            protected void onStart() {
                                super.onStart();
                                doProcessing();
                            }

                            @Override
                            public void onNext(String value) {

                            }

                            @Override
                            public void onError(Throwable e) {
                                finishProcessing();
                                new AlertDialog.Builder(getContext())
                                        .setMessage(e.getMessage())
                                        .create()
                                        .show();
                            }

                            @Override
                            public void onComplete() {
                                finishProcessing();
                                value.remove(res);

                                try {
                                    MassLossRecordListAdapter adapter = (MassLossRecordListAdapter) listview.getAdapter();
                                    adapter.notifyDataSetChanged();
                                } catch (Exception e) {
                                }

                                Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onEdit(QueryMassLossRecordsResponse res) {
                        Intent intent = new Intent(getActivity(), EditMassLossRecordActivity.class);
                        String parentId = "-1";
                        String childId = "";
                        String childName = "";
                        String enName = "";
                        String voyage = "";
                        String model = "";
                        String code = "";
                        String uri = "";

                        if ("配件".equals(res.getLoss_region())) {
                            parentId = "14";
                            childId = "";
                            childName = res.getLoss_reason().split("-")[0];
                            enName = res.getLoss_reason_en();
                        } else if ("附件包".equals(res.getLoss_region())) {
                            parentId = "15";
                        }

                        voyage = res.getVoyage_no();
                        model = res.getModel();
                        code = res.getModel_code();

                        intent.putExtra("parentId", parentId);
                        intent.putExtra("childId", childId);
                        intent.putExtra("childName", childName);
                        intent.putExtra("enName", enName);
                        intent.putExtra("voyageNo", voyage);
                        intent.putExtra("model", model);
                        intent.putExtra("modelCode", code);
                        intent.putExtra("uri", uri);
                        intent.putExtra("gson", new Gson().toJson(res));
                        startActivityForResult(intent, REQUEST_RECORD);

                    }
                }));
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(getActivity())
                        .setMessage(e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_RECORD) {
            load();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(vehicleInformationDetail.getClass().getCanonicalName(), new Gson().toJson(vehicleInformationDetail));
        super.onSaveInstanceState(outState);
    }
}
